var uname ;
var textArea;
var socketUrl;
var socket;
var tt;

var timeOutObj;

/**
 * 客户端到服务端协议 CS client-server
 * @type {{GAME_OVER: number, ADD_USER: number, MYSELF_FRAME: number, OPPONENT_FRAME: number, CANCEL_MATCH: number, MATCH_USER: number}}
 */
const CS_PROTOCOL = {
	//用户加入大厅
	ADD_USER:0x8000,
	//匹配对手
	MATCH_USER:0x8001,
	//取消匹配
	CANCEL_MATCH:0x8002,
	//我方帧
	MYSELF_FRAME:0x8003,
	//对手帧
	OPPONENT_FRAME:0x8004,
	//游戏结束
	GAME_OVER:0x8005
}

/**
 * 服务端到客户端协议 SC server-client
 * @type {{OPPONENT_IS_OPERATIING: number, SERVER_PUSH_OPPONENT_FRAME: number, MATCH_USER_RESPONSE: number, ADD_USER_RESPONSE: number, SERVER_PUSH_MYSELF_FRAME: number, GAME_OVER_RESPONSE: number, CONNECTION_SUCCESS: number}}
 */
const SC_PROTOCOL = {
	//建立 websocket 连接成功
	CONNECTION_SUCCESS:0x9000,
	//加入匹配大厅响应
	ADD_USER_RESPONSE:0x9001,
	//匹配对手响应
	MATCH_USER_RESPONSE:0x9002,
	//服务器推送本方帧
	SERVER_PUSH_MYSELF_FRAME:0x9003,
	//服务器推送对手帧
	SERVER_PUSH_OPPONENT_FRAME:0x9004,
	//结束游戏响应
	GAME_OVER_RESPONSE:0x9005,
	//对手正在操作
	OPPONENT_IS_OPERATIING:0x9006,
	//心跳
	HEART_BEAT:0x9007,
	//重连帧
	RECONNECT_FRAME:0x9008
}

function connect(){
	uname = $("#uname").val();
	textArea = document.getElementById('textArea');
	//测试url
	socketUrl="ws://localhost:8888/websocket/" + uname;
	//正式url
	// socketUrl="ws://peakgame.com.cn:8888/websocket/" + uname;

	if(typeof(WebSocket) == "undefined") {
		console.log("您的浏览器不支持WebSocket");
	}else{
		console.log("您的浏览器支持WebSocket");
		if(socket!=null){
			return;
		}

		try {
			socket = new WebSocket(socketUrl);
			init();
		} catch(e) {
			textArea.value += "connect catch error"+"\r\n";
			reconnect(socketUrl);
		}

	}
}

function disConnect(){
	socket.close();
	socket=null;
}

function init(){


	//打开事件
	socket.onopen = function() {
		textArea.value += "建立 websocket 连接"+"\r\n";
	};
	//获得消息事件
	socket.onmessage = function(msg) {

		var obj = JSON.parse(msg.data);
		if(obj.protocol === SC_PROTOCOL.CONNECTION_SUCCESS){

			//服务器响应,成功建立 websocket 连接
			textArea.value += msg.data+"\r\n";

		}else if(obj.protocol === SC_PROTOCOL.ADD_USER_RESPONSE){

			//服务器响应,用户加入大厅
			textArea.value += msg.data+"\r\n";

		}else if(obj.protocol === SC_PROTOCOL.MATCH_USER_RESPONSE){

			//服务器响应,用户匹配对手
			textArea.value += msg.data+"\r\n";
			$("#player1").text(uname);
			$("#player2").text(obj.data);

		}else if(obj.protocol === SC_PROTOCOL.SERVER_PUSH_MYSELF_FRAME){
			connectCheck.stop();
			//服务器推送本方帧
			textArea.value += msg.data+"\r\n";

			$("#text1").val(obj.data.text);
			$("#player1Steps").text(obj.data.steps);

		} else if(obj.protocol === SC_PROTOCOL.SERVER_PUSH_OPPONENT_FRAME){
			connectCheck.stop();
			//服务器推送对手帧
			textArea.value += msg.data+"\r\n";

			$("#text2").val(obj.data.text);
			$("#player2Steps").text(obj.data.steps);

		}else if(obj.protocol === SC_PROTOCOL.GAME_OVER_RESPONSE){
			//服务哦响应，结束游戏
			textArea.value += msg.data+"\r\n";

		}else if(obj.protocol === SC_PROTOCOL.OPPONENT_IS_OPERATIING){
			//服务器响应，你的对手正在操作，请稍后再试
			textArea.value += msg.data+"\r\n";

			alert("你的对手正在操作，请稍后再试");
		}else if(obj.protocol === SC_PROTOCOL.HEART_BEAT){

			textArea.value += msg.data+"\r\n";

		}
		else if(obj.protocol === SC_PROTOCOL.RECONNECT_FRAME){

			//重连帧
			textArea.value += msg.data+"\r\n";

			let myselfFrame = obj.data['myselfFrame'];
			let opponentFrame = obj.data['opponentFrame'];

			$("#text1").val(myselfFrame.text);
			$("#player1Steps").text(myselfFrame.steps);

			$("#text2").val(opponentFrame.text);
			$("#player2Steps").text(opponentFrame.steps);

		}

	};
	//关闭事件
	socket.onclose = function() {
		textArea.value += "websocket 连接关闭"+"\r\n";
		socket=null;
	};
	//发生了错误事件
	socket.onerror = function() {
		textArea.value += "websocket 发生了错误"+"\r\n";
		socket=null;
	}
}

var lockReconnect = false;//避免重复连接
function reconnect(url) {
	if(lockReconnect) {
		return;
	};
	lockReconnect = true;
	//没连接上会一直重连，设置延迟避免请求过多
	tt && clearTimeout(tt);
	tt = setTimeout(function () {
		connect(url);
		lockReconnect = false;
	}, 4000);
}

// //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
// window.onbeforeunload = function(){
// 	disConnect();
// };

//强制关闭浏览器  调用websocket.close（）,进行正常关闭
window.onunload = function() {
	disConnect();
};

// 用户进入匹配大厅
function addUser(){
	var packet = {};
	var sender = uname;
	var protocol = CS_PROTOCOL.ADD_USER;
	packet.sender = sender;
	packet.protocol = protocol;
	sendPacket(packet);
}

// 随机匹配
function matchUser(){
	var packet = {};
	var sender = uname;
	var protocol = CS_PROTOCOL.MATCH_USER;
	packet.sender = sender;
	packet.protocol = protocol;
	sendPacket(packet);
}

// 取消匹配
function cancelMatch(){
	var packet = {};
	var sender = uname;
	var protocol = CS_PROTOCOL.CANCEL_MATCH;
	packet.sender = sender;
	packet.protocol = protocol;
	sendPacket(packet);
}

//本方帧
function playMySelf(){

	let text1 = document.getElementById('text1').value;
	console.log("text1 =>" + text1);
	let steps = $("#player1Steps").text();
	console.log("steps =>" + steps);

	var packet = {};
	var sender = uname;
	var protocol = CS_PROTOCOL.MYSELF_FRAME;
	packet.sender = sender;
	packet.protocol = protocol;
	packet.gameFrame = {
		text:text1,
		steps:steps
	};
	connectCheck.start();
	sendPacket(packet);

}

//对手帧
function playOpponent(){

	let text2 = document.getElementById('text2').value;
	console.log("text2 =>" + text2);
	let steps = $("#player2Steps").text();
	console.log("steps =>" + steps);

	var packet = {};
	var sender = uname;
	var protocol = CS_PROTOCOL.OPPONENT_FRAME;
	packet.sender = sender;
	packet.protocol = protocol;
	packet.gameFrame = {
		text:text2,
		steps:steps
	};
	connectCheck.start();
	sendPacket(packet);

}

// 游戏结束
function gameOver(){
	var packet = {};
	var sender = uname;
	var protocol = CS_PROTOCOL.GAME_OVER;
	packet.sender = sender;
	packet.protocol = protocol;
	sendPacket(packet);
}

function sendPacket(packet){
	if(socket == null){
		console.log("websocket 未连接！")
		return;
	}
	socket.send(JSON.stringify(packet));
}

var connectCheck = {
	start: function (){
		timeOutObj = setTimeout(function () {
			if(socket != null && typeof(socket) != 'undefined'){
				socket.close();
				socket=null;
				textArea.value += "connectCheck 3秒后，服务端无响应，客户端断开连接 \r\n";
			}
		},3000);
	},
	stop: function (){
		if(timeOutObj != null && typeof(timeOutObj) != 'undefined'){
			clearTimeout(timeOutObj);
		}
	}
}

